<!--
描述：用户登录组件
开发人：桑杨
开发日期：2017年7月14日
-->

<template lang="pug">
  div.login(data-logig)
    div.hd
      .mn
        img(src="./logo-frame.png")
    div.bd
      div.from-warpper
        div.tit 登录
        div.form
          el-form.loginForm(v-bind:model="loginForm" v-bind:rules="rules" ref="loginForm"
          v-bind:show-message="false")
            el-form-item.kalix-form-item(prop="name")
              el-input(v-model="loginForm.name" placeholder="账号" ref="loginFormName")
                i.icon-users(slot="prefix")
            el-form-item.kalix-form-item(prop="pass")
              el-input(type="password" v-model="loginForm.pass" ref="loginFormPass" placeholder="密码" auto-complete="off")
                i.icon-lock(slot="prefix")
            div.error-message(v-if="error.flag") {{error.message}}
            el-form-item(label="")
              el-button.btn-submit(type="primary" v-on:click="onSubmit()" size="large") 登录
    div.ft
      .mn
        div Copyright&copy;2018   技术支持：吉林省行氏动漫科技有限公司
</template>

<script type="text/ecmascript-6">
  import Login from 'api/login'
  import {logoutUrl, applicationURL} from 'config/global.toml'
  import {mapMutations} from 'vuex'

  export default {
    name: 'LoginForm',
    data() {
      return {
        loginForm: {
          name: '',
          pass: ''
        },
        rules: {
          name: [
            {required: true, message: '请输入用户名', trigger: 'blur'},
            {min: 2, max: 8, message: '用户名长度在 2 到 8 个字符', trigger: 'blur'}
          ],
          pass: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ]
        },
        error: {
          flag: false,
          message: ''
        }
      }
    },
    activated() {
      this.loginForm = {name: '', pass: ''}
      console.log('this.$KalixEventBus', this.$KalixEventBus)
    },
    mounted() {
      let accessToken = this.$KalixCatch.get('access_token')
      if (accessToken && accessToken.length) {
        this.$http.get(logoutUrl)
          .then(res => {
            console.log('res', res)
          })
      }
      this.tabInput()
    },
    methods: {
      ...mapMutations({
        setCurrentUser: 'setCurrentUser',
        setMenuList: 'setMenuList',
        setNavigateTreeData: 'setNavigateTreeData'
      }),
      onSubmit(formName) {
        if (this._validateForm()) {
          this.login()
        }
      },
      login() {
        //  登录
        Login.remoteLogin({
          'username': this.loginForm.name,
          'password': this.loginForm.pass
        }).then(data => {
          if (data.success) {
            this.$KalixCatch.save('id', data.user.id)
            this.$KalixCatch.save('access_token', data.access_token)
            this.$KalixCatch.save('user_token', data.user.token)
            this.$KalixCatch.save('user_name', data.user.name)
            this.$KalixCatch.save('loginname', this.loginForm.name)
            // 在缓存中记录最后登录时间，处理单用户登录需求
            let now = new Date().getTime()
            this.$KalixCatch._saveLocal('lastLoginTime', now)
            this.$KalixCatch.save('lastLoginTime', now)
            data.user.loginname = this.loginForm.name
            this.setCurrentUser(data.user)
            this._getMenu(() => {
              this.$router.push({path: '/'})
            })
          } else {
            this.$refs.loginFormName.focus()
            this.$KalixMessage.error(data.message)
          }
        }).catch(error => {
          console.log('login error ', error)
          this.$refs.loginFormName.focus()
          this.$KalixMessage.error(error.message)
        })
      },
      _validateForm() {
        //  验证表单
        for (let key in this.rules) {
          this.error.flag = false
          this.error.message = ''
          this.$refs.loginForm.validateField(key, errorMessage => {
            //  如果错误信息长度 > 0 表示验证不通过
            this.error.flag = errorMessage.length > 0
            this.error.message = errorMessage
          })
          if (this.error.flag) {
            return false
          }
        }
        return true
      },
      tabInput() {
        let ipts = document.getElementsByClassName('el-input__inner')
        for (let i = 0; i < ipts.length; i++) {
          ipts[i].addEventListener('keydown', e => {
            if (e.keyCode === 13) {
              if (ipts[i + 1]) {
                ipts[i + 1].focus()
              } else {
                document.getElementsByClassName('btn-submit')[0].focus()
              }
            }
          })
        }
      },
      listen() {
        this.error.flag = false
      },
      _getMenu(callBack) {
        this.treeListData = {}
        this.menu = []
        this.$http.get(applicationURL, {
          params: {
            _dc: (new Date()).getTime(),
            page: 1,
            start: 0,
            limit: 25
          }
        }).then(res => {
          if (res && res.data) {
            console.log('[res] data:', res.data)
            this.menu = res.data
            this.setMenuList(this.menu)
            this.setList(0, () => {
              console.log(this.treeListData)
              this.setNavigateTreeData(this.treeListData)
              callBack()
            })
          }
        })
      },
      setList(index, callBack) {
        if (index < this.menu.length) {
          let item = this.menu[index]
          let key = item.id
          let _treeData = []
          this.$http.get(`${applicationURL}/${key}`,
            {
              params: {
                _dc: (new Date()).getTime(),
                node: 'root'
              }
            })
            .then(res => {
              if (res.data && res.data.code !== 401) {
                _treeData = res.data
                _treeData.map(e => {
                  this.$set(e, 'isShow', false)
                })
                console.log('this.treeListData[key]', key)
                this.treeListData[key] = _treeData
                this.setList(index += 1, callBack)
              }
            })
        } else {
          callBack()
        }
      }
    },
    components: {},
    computed: {},
    watch: {
      loginForm: {
        handler: 'listen',
        // 深度观察
        deep: true
      }
    }
  }
</script>
